import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ScrollView, View } from '@tarojs/components'
import { useSelector } from 'react-redux'
import Taro, { useShareAppMessage, useShareTimeline, useAddToFavorites, useRouter, useTabItemTap, useDidShow } from '@tarojs/taro'
import managementPlanActions from '@ACTIONS/managementPlan'
import patientActions from '@ACTIONS/patient'
import withWebLogin from '@HOC/withWebLogin'
import shareManage from '@UTILS/shareManage'
import i18n from '@I18N'
import Navigate from '@NAVIGATION/navigateManager'
import dataCenterActions from '@ACTIONS/dataCenter'
import {
  convertPx,
  getPlatform,
  getRouterValue,
  getWindowHeight,
  handleClickTab,
  showToast
} from '@UTILS/common'
import { getGlobalData } from '@UTILS/globalData'
import MyPainManagement from '@COMPONENTS/PlanManagement/MyPainManagement'
import api from '@API'
import { getWeRunData } from '@UTILS/wx'
import NavBar from '@COMPONENTS/NavBar/NavBar'
import DBConfig from '@CONFIG/DBConfig'
import PlanGuide from '@COMPONENTS/PlanManagement/PlanGuide'
import { HomeTopBtn } from '@COMPONENTS/PlanManagement/PlanGuidDesc'
import ContactButton from '@COMPONENTS/Button/ContactButton'
import HomeStep from '@COMPONENTS/Home/HomeStep'
import HomeStepPanel from '@COMPONENTS/Home/HomeStepPanel'
import { getStorageSync } from '@UTILS/localStorage'
import { Analytic_Type } from '@CONSTANTS/analytic'
import { ROUTER_SCENE_TITLE, SHARE_TYPE } from '@CONSTANTS/app'
import Scenes, { RouteSceneKey } from '@NAVIGATION/scenes'
import LoadingView from '@COMPONENTS/LoadingView'
import HomeAllPopUp from '@COMPONENTS/HomePopUp/HomeAllPopUp'
import { STORAGE_KEY } from '@CONSTANTS/common'
import { useRequest } from '@HOOKS/useRequest'
import useSpringRainLogin from '@HOOKS/useSpringRainLogin'
import style from './index.module.scss'

const { isWeb, isWX } = getPlatform()
interface Props {
  showLogin: () => void
}
const Index: React.FC<Props> = ({ showLogin }) => {
  const language = 'zh'
  useSpringRainLogin()
  const hasSaveMyInviter = useRef(false)
  const router = useRouter()
  const title = DBConfig.careEnvType === 'prod' ? '疼爱健康' : `疼爱健康${DBConfig.careEnvType}`
  const [barContent, setBarContent] = useState<JSX.Element | null>(null)
  const { code, planId, planTitle, shareType, invitorUserId } = useMemo(() => router.params, [router])
  const [height, setHeight] = useState(Number(getWindowHeight(isWeb)))
  const [showStep, setShowStep] = useState(false)
  const [showStepPanel, setShowStepPanel] = useState(false)
  const acquireChannel = useMemo(() => getRouterValue('AcquireChannel'), [])
  const hideRecommendPlan = useMemo(() => (isWeb && (getGlobalData('isTakeda') || acquireChannel === 'takeda')), [acquireChannel])
  const {
    myPainManagement, homePageSpotEvents, loadingHomePageSpotEvents, loadingMyPainManagement
  } = useSelector(state => state.managementPlan)
  const {
    dispatchGetMyPainManagement, dispatchGetRecommendGoodsEvents, dispatchGetHomePersonaEvents,
    dispatchGetHomePageSpotEvents, dispatchGetHomePainDes, dispatchGetAllHomeEvents
  } = managementPlanActions
  const isVisitor = useSelector(state => state.profile.isVisitor)
  const { isDisabledConsultation } = useSelector(state => state.auth)
  const { dispatchGetMyPatients } = patientActions
  const { dispatchSaveWeChatStepRecords, dispatchGetMyLastestExpiredPlan } = dataCenterActions
  const getMyPainManagement = useRequest(dispatchGetMyPainManagement)
  const getRecommendGoodsEvents = useRequest(dispatchGetRecommendGoodsEvents)
  const getHomePersonaEvents = useRequest(dispatchGetHomePersonaEvents)
  const getHomePageSpotEvents = useRequest(dispatchGetHomePageSpotEvents)
  const getAllHomeEvents = useRequest(dispatchGetAllHomeEvents)
  const getHomePainDes = useRequest(dispatchGetHomePainDes)
  const getMyPatients = useRequest(dispatchGetMyPatients)
  const getMyLastestExpiredPlan = useRequest(dispatchGetMyLastestExpiredPlan)
  const saveWeChatStepRecords = useRequest(dispatchSaveWeChatStepRecords)
  const p8Id = useSelector(state => state.profile?.user?.p8Id)
  const user = useSelector(state => state.profile.user)
  const isSameAccount = !!invitorUserId && invitorUserId === p8Id
  const { Title, HasPainManagement } = myPainManagement
  const fetchData = useCallback(() => {
    if (!p8Id) return
    getMyPainManagement()
    getMyPatients()
    getRecommendGoodsEvents()
    getAllHomeEvents()
    getHomePersonaEvents()
    getHomePageSpotEvents()
    getHomePainDes()
    getMyLastestExpiredPlan()
  }, [getAllHomeEvents, getHomePageSpotEvents, getHomePainDes, getHomePersonaEvents, getMyPainManagement,
    getMyPatients, getRecommendGoodsEvents, p8Id, getMyLastestExpiredPlan])

  const updateStep = useCallback(() => {
    if (isVisitor || !isWX) return
    Taro.getSetting({
      success: async res => {
        const runStatus = res.authSetting['scope.werun']
        if (!runStatus) return
        const runData = await getWeRunData()
        const hasData = runData?.length > 0
        hasData && saveWeChatStepRecords(runData)
      }
    })
  }, [saveWeChatStepRecords, isVisitor])
  const initH5OpenId = useCallback(async () => {
    if (!isWeb || !code) return
    try {
      const result = await api.getWeChatOpenId({ code })
      await Taro.setStorage({
        key: 'wx_openid',
        data: result.OpenId
      })
      Navigate.navigateBack(1)
    } catch (e) {
      showToast(e)
    }
  }, [code])
  const saveMyInviter = useCallback(async () => {
    try {
      if (!invitorUserId || isSameAccount) return
      if (hasSaveMyInviter.current) return
      await api.saveMyInviter({ InviterUserId: invitorUserId })
      hasSaveMyInviter.current = true
    } catch (e) {
      showToast(e)
    }
  }, [invitorUserId, isSameAccount])
  const onCloseStepFun = useCallback(() => {
    setShowStep(false)
    setShowStepPanel(false)
  }, [])

  const onClickStepFun = useCallback(() => {
    setShowStepPanel(true)
    Taro.tracker.trackEvent(Analytic_Type.num_home_step.eventId)
  }, [])

  const onClosePanelFun = useCallback(() => {
    setShowStepPanel(false)
  }, [])

  const showTitle = HasPainManagement ? Title?.[language] : title
  const scrollContent = useMemo(() => ([
    {
      scrollHeight: 120,
      content: <HomeTopBtn title={showTitle} />
    },
    {
      scrollHeight: 624,
      content: <HomeTopBtn homePageSpotEvents={homePageSpotEvents} title={showTitle} showLogin={showLogin} showBtn />
    },
  ]), [homePageSpotEvents, showLogin, showTitle])
  const onScroll = useCallback(({ detail }) => {
    const { scrollTop } = detail
    const { scrollHeight, content } = scrollContent[HasPainManagement ? 0 : 1]
    if (scrollTop > scrollHeight) {
      setBarContent(content)
      return
    }
    setBarContent(null)
  }, [HasPainManagement, scrollContent])
  useEffect(() => {
    if (!p8Id) return
    saveMyInviter()
  }, [p8Id, saveMyInviter])

  useEffect(() => {
    initH5OpenId()
    if (isVisitor) return
    updateStep()
  }, [initH5OpenId, isVisitor, updateStep])

  const isRequest = useRef(false)
  useEffect(() => {
    if (loadingMyPainManagement || isRequest.current) return
    isRequest.current = true
    Taro.tracker.trackEvent(Analytic_Type.tap_home_visitor.eventId,
      { IsJoinPlan: HasPainManagement || false },
      { Scene: RouteSceneKey.homePage })
  }, [HasPainManagement, loadingMyPainManagement, title])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  useEffect(() => {
    async function showStepModal() {
      const show = await getStorageSync(STORAGE_KEY.showStepModal)
      if (show === '' && getPlatform().isWX) {
        Taro.setStorage({
          key: STORAGE_KEY.showStepModal,
          data: true
        })
        setShowStep(true)
      }
    }
    showStepModal()
  }, [])

  useEffect(() => {
    if (HasPainManagement) {
      setBarContent(null)
    }
  }, [HasPainManagement])

  useTabItemTap(item => {
    handleClickTab(`/${item.pagePath}`)
  })

  useShareAppMessage(() => {
    Taro.tracker.trackEvent(Analytic_Type.tap_wmp_share.eventId,
      { SceneTitle: ROUTER_SCENE_TITLE.homePage, ShareType: SHARE_TYPE.WeChatFriend, IsJoinPlan: HasPainManagement },
      { Scene: RouteSceneKey.homePage })
    return shareManage.onShareAppMessage.homePage(i18n.share.home_title(), myPainManagement, user)
  })

  useShareTimeline(() => {
    Taro.tracker.trackEvent(Analytic_Type.tap_wmp_share.eventId,
      { SceneTitle: ROUTER_SCENE_TITLE.homePage, ShareType: SHARE_TYPE.WeChatMoment, IsJoinPlan: HasPainManagement },
      { Scene: RouteSceneKey.homePage })
    return shareManage.onShareTimeline.homePage(i18n.share.home_title(), myPainManagement, user)
  })

  useAddToFavorites(() => shareManage.onAddToFavorites.homePage(i18n.share.home_title(), myPainManagement, user))
  useDidShow(() => {
    Taro.removeStorageSync(STORAGE_KEY.meditation_is_today)
    setTimeout(() => {
      const currHeight = Number(getWindowHeight(isWeb))
      if (currHeight <= height) return
      setHeight(currHeight)
    }, 200)
  })

  const onClickItemTab = useCallback(path => {
    if (path !== Scenes.homePage) return
    if (p8Id) {
      getMyPainManagement()
    }
  }, [p8Id, getMyPainManagement])
  useEffect(() => {
    Taro.eventCenter.on('onClickTab', onClickItemTab)
    return () => {
      Taro.eventCenter.off('onClickTab', onClickItemTab)
    }
  }, [onClickItemTab])
  const backgroundColor = barContent ? 'white' : 'transparent'
  const navBarContent = barContent || <View />
  const titleColor = '#333'
  const scrollVirtualHeight = showStep ? 88 : 0
  const scrollVirtualHeightPX = scrollVirtualHeight * Taro.getSystemInfoSync().windowWidth / 750
  const scrollStyle = { height: convertPx(height) }
  if (loadingHomePageSpotEvents || loadingMyPainManagement) {
    return <LoadingView />
  }
  return (
    <View className={style.container}>
      {!HasPainManagement && <ContactButton btnContainer={style.btnContainer} />}
      <NavBar
        showIcon={false}
        title={showTitle}
        backgroundColor={backgroundColor}
        titleColor={titleColor}
        barContent={navBarContent}
      />
      <ScrollView scrollY style={scrollStyle} onScroll={onScroll} className={style.scroll}>
        <View className={style.scrollContent}>
          {HasPainManagement ? (
            <MyPainManagement
              virtualHeight={scrollVirtualHeight}
              language={language}
              showLogin={showLogin}
              hideRecommendPlan={hideRecommendPlan}
            />
          ) : (
            <PlanGuide
              virtualHeight={scrollVirtualHeight}
              language={language}
              height={convertPx(height + scrollVirtualHeightPX)}
              showTitle={showTitle}
              showLogin={showLogin}
              isDisabledConsultation={isDisabledConsultation}
            />
          )}
        </View>
      </ScrollView>
      <View>
        {showStep ? <HomeStep onCloseFun={onCloseStepFun} onClickFun={onClickStepFun} showTriangle={!showStepPanel} /> : null}
        {showStepPanel ? <HomeStepPanel onCloseFun={onClosePanelFun} /> : null}
      </View>
      <HomeAllPopUp
        type={shareType}
        isSameAccount={isSameAccount}
        planId={planId}
        planTitle={planTitle}
        showLogin={showLogin}
      />
    </View>
  )
}

export default withWebLogin(Index)
